package com;

import com.netflix.config.ConfigurationManager;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;

public class CurcuitBreakerCloseDemo extends HystrixCommand<String>{
	// 设置超时的时间为500毫秒
	public CurcuitBreakerCloseDemo() {
	    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HystrixGroup"))
	            .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
	            		.withExecutionTimeoutInMilliseconds(500))
	    		);
	}

	protected String run() throws Exception {
		// 模拟处理超时
		Thread.sleep(500);
		return "Run";
	}

	@Override
	protected String getFallback() {
		return "FallBack";
	}

	public static void main(String[] args) throws Exception {
		// 10秒内有5个请求
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.metrics.rollingStats.timeInMilliseconds", 10000);
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.circuitBreaker.requestVolumeThreshold", 5);
		ConfigurationManager.getConfigInstance().setProperty(
				"hystrix.command.default.circuitBreaker.errorThresholdPercentage", 50);
		for(int i = 0; i < 10; i++) {
			// 执行的命令全部都会超时
			CurcuitBreakerCloseDemo c = new CurcuitBreakerCloseDemo();
			c.execute();
			// 断路器打开后输出信息
			if(c.isCircuitBreakerOpen()) {
				System.out.println("Curcuit Breaker is open，running " + (i + 1) + " case");
			}
		}
	}
}
